// 分组：数组对象，按照某个属性分组
export const getGroupObject = (list, attr) => {
    const map = new Map();
    list.forEach((item, index, arr) => {
        if (!map.has(item[attr])) {
            map.set(
                item[attr],
                arr.filter(a => a[attr] == item[attr])
            );
        }
    });
    return Object.fromEntries(Array.from(map).map(item => [item[0], item[1]]));
}

// 锚点：跳转到指定锚点位置
export const scrollToSection = (id) => {
    let section = document.getElementById(id)
    if (section) {
        section.scrollIntoView()
    }
}
export function defaultTableData(row, column, cellValue) {
    return (cellValue || cellValue === 0) ? cellValue : '-';
}

//字典根据key取name
let dictObj = JSON.parse(localStorage.getItem('dataDictionary')) || [];
export function getDicName(typeName, data) {
    let target = dictObj[typeName].find(item => item.dictValue == data);
    return target ? target.dictLabel || '-' : '-';
}

export function diffTime(time) {
    if (!time) {
        return '-'
    }
    let now = Date.now() / 1000
    let diff = parseInt(Math.abs(now - time))
    if (diff < 3600 * 24) {
        return Math.floor(diff / 3600) + '小时'
    } else {
        let daty = Math.floor(diff / (3600 * 24))
        let hours = Math.floor((diff - 3600 * 24 * daty) / 3600)
        return daty + '天' + hours + '小时'
    }
}
// 日期格式化
export function parseTime(time, cFormat) {
    if (arguments.length === 0) {
        return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
        date = time
    } else {
        if (('' + time).length === 10) time = parseInt(time) * 1000
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str
}
// 获取随机字母
export function randomCoding(num, type) {
    var result = [];
    let typeObj = {
        number: () => {
            for (var i = 0; i < num; i++) {
                var randNum = Math.ceil(Math.random() * 10);
                result.push(randNum)
            }
        },
        letter: () => {
            for (var i = 0; i < num; i++) {
                var ranNum = Math.ceil(Math.random() * 25);
                result.push(String.fromCharCode(65 + ranNum));
            }
        },
        numLetter: () => {
            for (var i = 0; i < num.num; i++) {
                var numItem = Math.ceil(Math.random() * 10);
                result.push(numItem);
            }
            for (var j = 0; j < num.letter; j++) {
                var ranNum = Math.ceil(Math.random() * 25);
                result.push(String.fromCharCode(65 + ranNum));
            }
        }
    }
    typeObj[type]()
    return result.join('');
}
// 获取url指定参数
export function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return (false);
}
// 深拷贝
export function deepClone(source) {
    if (!source && typeof source !== 'object') {
        throw new Error('error arguments', 'shallowClone')
    }
    const targetObj = source.constructor === Array ? [] : {}
    for (const keys in source) {
        // eslint-disable-next-line no-prototype-builtins
        if (source.hasOwnProperty(keys)) {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = source[keys].constructor === Array ? [] : {}
                targetObj[keys] = deepClone(source[keys])
            } else {
                targetObj[keys] = source[keys]
            }
        }
    }
    return targetObj
}
/**
 * 下载文件(流)
 */
export function downloadNewFile(obj, name) {
    const url = window.URL.createObjectURL(new Blob([obj]))
    console.log(url)
    const link = document.createElement('a')
    link.style.display = 'none';
    link.href = url;
    // const fileName = name+"."+suffix;
    link.setAttribute("downLoad", name);
    document.body.append(link);
    link.click();
    document.body.removeChild(link);
}

/**
 *
 * @param {String} url 文件地址下载
 */
export function downloadFileUrl(url) {
    const link = document.createElement('a')
    link.setAttribute('download', '')
    link.setAttribute('href', url)
    link.click()
}

export function downloadOpenFileUrl(url) {
    window.open(url)
}

// 千分位分隔符
export function formatArea(val, decimal = 2) {
    if (!val && val !== 0) return "";
    let reg = /^-{0,1}(|\d*|(\d*\.\d*))$/;
      if (reg.test(val)) {
      var valArr = decimal
        ? String(decimalRound(val,Number(decimal))).split(".")
        : String(val).split(".");
      var format = valArr[0].replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
      return valArr[1] == null ? format : format + "." + valArr[1];
    } else {
      // console.warn(`splitFormat val(${val}) is not 0-9 integer or decimal`);
      return val
    }
  }

// 小数四舍五入
export function decimalRound(num, digit = 2) {
    let reg = /^-{0,1}(|\d*|(\d*\.\d*))$/;
    if(!reg.test(num) || digit < 0) return num
    if (digit == 0) return Math.round(num)
    const multiplier = Math.pow(10, digit);
    let roundedNum = Math.round(num * multiplier) / multiplier;
    let strNum = roundedNum.toString().split('.');
    if (strNum.length > 1 && strNum[1].length < digit) {
        strNum[1] += '0'.repeat(digit - strNum[1].length);
    } else if (strNum.length === 1) {
        strNum.push('0'.repeat(digit));
    }
    return strNum.join('.');
  }

//阿拉伯数字转大写，整数转大写
export function numToCapital(num, type = '') {
    if (!num) return 0
    const strNum = Number((num + '').replace(/[,，]*/g, '')) + '' // 记录字符
    num = parseInt(Number(strNum)) // 转为整数，
    let capitalAr = '零一二三四五六七八九十'
    let unitAr = ['十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千']
    if (type) {
        capitalAr = '零壹贰叁肆伍陆柒捌玖拾'
        unitAr = ['拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟'] // 单位
    }
    const resultAr = [] // 记录结果，后边json.in就可
    let index = strNum.length - 1 //记录位数
    let idx = 0 // 记录单位
    let percent = 10
    const turnNum = (num, percent, index) => {
        const unit = num / percent
        const capital = capitalAr[Number(strNum[index])]
        if (unit < 1) {
            resultAr.push(capital)
            // 出现11【一十一】这种情况
            if (Number(strNum[index]) === 1 && (strNum.length === 2 || strNum.length === 6 || strNum.length === 10)) {
                resultAr.pop()
            }
            return false //结束递归
        } else {
            if (capital === '零') {
                // 万和亿单位不删除
                if (!['万', '亿'].includes(resultAr[resultAr.length - 1])) {
                    resultAr.pop()
                }
                // 前面有零在删掉一个零
                if (resultAr[resultAr.length - 1] === '零') {
                    resultAr.pop()
                }
            }
            resultAr.push(capital)
            // 过滤存在【零万】【零亿】这种情况
            if (['万', '亿'].includes(resultAr[resultAr.length - 2]) && capital === '零') {
                resultAr.pop()
            }
            // 过滤【1亿万】这种情况
            if (resultAr[0] === '万' && resultAr[1] === '亿') {
                resultAr.shift()
            }
            // 末尾【零】删掉
            if (resultAr[0] === '零') {
                resultAr.pop()
            }
            resultAr.push(unitAr[idx++])
            turnNum(num, percent * 10, --index)
        }
    }
    turnNum(num, percent, index)
    return resultAr.reverse().join('')
}


/**
 * 扁平化转树
 * @param {*} list       数据
 * @param {*} parentKey  父级标识Key
 * @param {*} curKey     当前字段查找Key
 * @param {*} parentData 父级数据
 * @param {*} callBack   回调
 * @returns 
 */
export function listToTree(list,parentKey,curKey,parentData,callBack) {
    let treeData = []
    let curNo = 1
    let index = 0;
    list.forEach(el=>{
      if (parentData) {
        if (el[parentKey] == parentData[curKey]) {
          el.customNo = parentData.customNo + '.' + curNo++
          el.curParentIndex = parentData.curParentIndex;
          if (callBack) {
            callBack(el,parentData)
          }
          el.children = listToTree(list,parentKey,curKey,el,callBack)
          treeData.push(el)
        }
      } else {
        if (!el[parentKey] || el[parentKey] == 0) {
          el.customNo = curNo++
          el.curParentIndex = index++;
          if (callBack) {
            callBack(el)
          }
          el.children = listToTree(list,parentKey,curKey,el,callBack)
          treeData.push(el)
        }
      }
    })
    return treeData
  }

//全屏 | 退出全屏 element 操作的容器
export function requestFullScreen(element) {
    if (!document.fullscreenElement) {
        // 进入全屏
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.mozRequestFullScreen) {
            // Firefox
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullscreen) {
            // Chrome, Safari, Opera
            element.webkitRequestFullscreen();
        } else if (element.msRequestFullscreen) {
            // IE/Edge
            element.msRequestFullscreen();
        }
    } else {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.mozCancelFullScreen) {
            // Firefox
            document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
            // Chrome, Safari, Opera
            document.webkitExitFullscreen();
        } else if (document.msExitFullscreen) {
            // IE/Edge
            document.msExitFullscreen();
        }
    }
}

export function isIpad() {
    return /iPad|Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;
}

// 浏览器直接预览oss文件
export function previewFile(fileUrl) {
    let endcodeUrl = encodeURIComponent(fileUrl)
    const url = `https://view.officeapps.live.com/op/view.aspx?src=${endcodeUrl}`
    window.open(url)
}

//二维数组加排序
export function setOrder(list) {
	let order = 0;
	list.forEach(item => {
		if (item.list && item.list.length > 0) {
			item.list.forEach(child => {
				child.order = order;
				order++;
			});
		} else {
			item.order = order;
			order++;
		}
	});
}

//判断平年润年
const isLeapYear = function (year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		return true;
	} else {
		return false;
	}
};

//计算两个日期之间 相差几年几月几日
export function monthDayDiff(startTime, endTime) {
	if (startTime >= endTime) {
		return {
			year: 0,
			month: 0,
			day: 0,
		};
	}
	let flag = [1, 3, 5, 7, 8, 10, 12, 4, 6, 9, 11, 2];
	let start = new Date(startTime);
	let end = new Date(endTime);
	let year = end.getFullYear() - start.getFullYear();
	let month = end.getMonth() - start.getMonth();
	let day = end.getDate() + 1 - start.getDate();
	if (month < 0) {
		year--;
		month = end.getMonth() + (12 - start.getMonth());
	}
	if (day < 0) {
		month--;
		let isLeapYearFlag = isLeapYear(start.getFullYear());
		let index = flag.findIndex(temp => {
			return temp === start.getMonth() + 1;
		});
		let monthLength;
		if (index <= 6) {
			monthLength = 31;
		} else if (index > 6 && index <= 10) {
			monthLength = 30;
		} else {
			monthLength = isLeapYearFlag ? 29 : 28;
		}
		day = end.getDate() + (monthLength - start.getDate());
	} else {
		let isLeapYearFlag = isLeapYear(end.getFullYear());
		let index = flag.findIndex(temp => {
			return temp === end.getMonth() + 1;
		});
		let monthLength;
		if (index <= 6) {
			monthLength = 31;
		} else if (index > 6 && index <= 10) {
			monthLength = 30;
		} else {
			monthLength = isLeapYearFlag ? 29 : 28;
		}
		if (day == monthLength) {
			day = 0;
			month = month + 1;
		}
	}
	return {
		year: year,
		month: month,
		day: day,
	};
}